import AppConfig from "../../config/app.config";
import {ModelConfig} from "./type";
import {Response} from "express";

const crypto = require('crypto');
const Decimal = require('decimal.js');
const fs = require('fs'); // 导入 fs 模块
const path = require('path'); // 导入 path 模块
export const mkdir = (pathname: string) => {
    if (!fs.existsSync(pathname)) {
        fs.mkdirSync(pathname)
    }
}
export const copyDir = (originPath: string, targetPath: string) => {
    fs.readdir(originPath,{withFileTypes:true},(err,files)=>{
        for(let file of files){
            //判断是否是文件夹，不是则直接复制文件到newFile中
            if(!file.isDirectory()){
                //获取旧文件夹中要复制的文件
                const OriginFile = path.resolve(originPath,file.name)
                //获取新文件夹中复制的地方
                const CopyFile = path.resolve(targetPath,file.name)
                //将文件从旧文件夹复制到新文件夹中
                fs.copyFileSync(OriginFile,CopyFile)
            }else{//如果是文件夹就递归变量把最新的文件夹路径传过去
                const CopyDirPath = path.resolve(targetPath,file.name)
                const OriginDirPath = path.resolve(originPath,file.name)
                fs.mkdir(CopyDirPath,(err)=>{

                })
                // OriginFilePath = OriginPath
                // CopyFilePath = DirPath
                copyDir(OriginDirPath,CopyDirPath)
            }
        }
    })
}
export const listToTree = (list, childrenKey: string = 'children', itemIdKey: string = 'id', parentIdKey: string = 'parentId', parentId?: string) => {
    let menuObj = {}
    list.forEach(item => {
        item[childrenKey] = []
        menuObj[item[itemIdKey]] = item
    })
    return list.filter(item => {
        if (item[parentIdKey] !== parentId) {
            menuObj[item[parentIdKey]][childrenKey].push(item)
            return false
        }
        return true
    })
}

export const generateRandomTokenBase64 = (length = 64) => {
    const randomBytes = crypto.randomBytes(length);
    return randomBytes.toString('base64'); // 转换为 Base64 字符串
}
export const encrypt = (text: string, secretKey: string) => {
    const iv = Buffer.from(AppConfig.iv, 'hex'); // 初始化向量
    const key = crypto.createHash('sha256').update(secretKey).digest('base64').substr(0, 32);
    const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted
}

// 解密
export const decrypt = (encrypted: string, secretKey: string): String => {
    const iv = Buffer.from(AppConfig.iv, 'hex'); // 初始化向量
    const key = crypto.createHash('sha256').update(secretKey).digest('base64').substr(0, 32);
    const encryptedText = Buffer.from(encrypted, 'hex');
    const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
    let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

export const setErrorStreamRes = (msg: string, res: Response) => {
    res.write('data: '+JSON.stringify({error: msg})+'\n\n')
    setTimeout(() => {
        res.end('')
    }, 150)
}
